class Book < ActiveRecord::Base
  belongs_to :category
  belongs_to :language

  has_many :borrowings

  has_many :books, :through => :borrowings

  validates_presence_of :title, :catalog_no, :category_id, :language_id
  validates_uniqueness_of :catalog_no

  acts_as_dropdown  :text => "title", :order => "title"

  STATE_AVAILABLE  = 1
  STATE_BORROWED  = 2
  STATE_BLOCKED  = 3

  before_create { |me| me.state = STATE_AVAILABLE }

  indexes_columns :title, :author, :catalog_no, :isbn, :into=>'idx'

  before_save :make_index
  before_update :make_index

  def make_index
    self.idx = self.index_repr
  end

  def can_destroy?
    @borrowings = Borrowing.find(:all, :conditions => ["book_id = ?", self.id])
    return @borrowings.empty?
  end
end
